package com.yyhh.helpcall.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

//import com.nbsp.materialfilepicker.MaterialFilePicker;
//import com.nbsp.materialfilepicker.ui.FilePickerActivity;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.yyhh.helpcall.MainApplication;
import com.yyhh.helpcall.R;
import com.yyhh.helpcall.base.RecordConfig;
import com.yyhh.helpcall.http.OkHttpUtils;
import com.yyhh.helpcall.http.bean.BaseResponse;
import com.yyhh.helpcall.utils.AppUtils;
import com.yyhh.helpcall.utils.FileUtil;
import com.yyhh.helpcall.utils.NetLog;
import com.yyhh.helpcall.utils.ScanRecordUtils;
import com.yyhh.helpcall.utils.SpUtils;
import com.yyhh.helpcall.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.rosuh.filepicker.config.FilePickerManager;

public class SplashActivity extends BaseActivity {
//    Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ? new String[]{
//        Manifest.permission.WRITE_CALL_LOG,
//                Manifest.permission.READ_CALL_LOG,
//                Manifest.permission.READ_PHONE_STATE,
//                Manifest.permission.READ_EXTERNAL_STORAGE,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.CALL_PHONE,
//                Manifest.permission.ANSWER_PHONE_CALLS,
//                Manifest.permission.PROCESS_OUTGOING_CALLS,
//                Manifest.permission.MANAGE_EXTERNAL_STORAGE
//    } :


    private static String[] permissions = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? new String[]{
                    Manifest.permission.WRITE_CALL_LOG,
                    Manifest.permission.READ_CALL_LOG,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.ANSWER_PHONE_CALLS,
                    Manifest.permission.PROCESS_OUTGOING_CALLS,
            } : new String[]{
                    Manifest.permission.WRITE_CALL_LOG,
                    Manifest.permission.READ_CALL_LOG,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.PROCESS_OUTGOING_CALLS,
            };

    private Handler handler = new Handler();
    public static final String TARGET_PATH = "targetFilePath";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        PermissionX.init(this)
                .permissions(permissions)
                .request(new RequestCallback() {
                    @Override
                    public void onResult(boolean allGranted, List<String> grantedList, List<String> deniedList) {
                        if (allGranted) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
//                                    initDatas();

//                                    handler.postDelayed(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            goToPage();
//                                        }
//                                    },3000);

                                    //先判断本地是否选中过目标路径
                                    String path = SpUtils.getInstance(SplashActivity.this).getString(SplashActivity.TARGET_PATH);
                                    if (TextUtils.isEmpty(path)) {
                                        initDatas2();
                                    } else {
                                        MainApplication.recordConfig = new RecordConfig(path, "", "");
                                        goToPage();
                                    }
                                }
                            }, 1000);
                        } else {
                            AppUtils.openAPPSettings(SplashActivity.this);
                            ToastUtils.show("请到设置页面开启必要的权限");
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
            try {
                List<String> paths = FilePickerManager.INSTANCE.obtainData();
                NetLog.d("onActivityResult = " + paths.toString());
                String path = paths.get(0);
//                String path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
//                NetLog.d("onActivityResult = " + path);
                File file = new File(path);
                File targetFile = null;

                boolean isMatching = false;

                if (file.isDirectory()) {
                    targetFile = file;
                    isMatching=true;
                } else {
                    targetFile = file.getParentFile();
                    File[] files = targetFile.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        File file2 = files[i];
                        if (file2.getName().endsWith(".wav")
                                || file2.getName().endsWith(".m4a")
                                || file2.getName().endsWith(".amr")
                                || file2.getName().endsWith(".mp3")) {
                            isMatching = true;
                            break;
                        }
                    }
                }

                if (isMatching) {
                    //匹配成功
                    SpUtils.getInstance(SplashActivity.this).putString(SplashActivity.TARGET_PATH, targetFile.getAbsolutePath());
                    MainApplication.recordConfig = new RecordConfig(targetFile.getAbsolutePath(), "", "");
                    goToPage();

                    //接口上报
                    HashMap<String, String> map = new HashMap<>();
                    map.put("dir", targetFile.getAbsolutePath().replace("/storage/emulated/0", ""));
                    OkHttpUtils.getInstance().getApi().upPhoneDir(map)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<BaseResponse<Object>>() {
                                @Override
                                public void accept(BaseResponse<Object> objectBaseResponse) throws Exception {

                                }
                            });
                } else {
                    //匹配失败
                    ToastUtils.show("您选择的文件夹下面没有录音文件，请开启自动录音通话后，拨打电话生成录音文件后再选择");
                    showDialog();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("系统检测到您的手机未进行适配,请手动选择录音文件夹")
                .setCancelable(false)
                .setPositiveButton("选择录音目录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        new MaterialFilePicker().withActivity(SplashActivity.this).withRequestCode(200).start();
                        FilePickerManager.INSTANCE
                                .from(SplashActivity.this)
                                .skipDirWhenSelect(false)
                                .enableSingleChoice()
                                .forResult(200);
                    }
                })
                .create()
                .show();
    }

    /**
     * 第二套匹配规则
     */
    private void initDatas2() {
        HashMap<String, String> map = new HashMap<>();
        OkHttpUtils.getInstance().getApi().phoneDirs(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<ArrayList<String>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<ArrayList<String>> value) {
                        if (value.isSuccess()) {
                            String path = FileUtil.findFilePathExist(value.data);
                            if (TextUtils.isEmpty(path)) {
                                showDialog();
                            } else {
                                //不为空则表示匹配到了目录
                                SpUtils.getInstance(SplashActivity.this).putString(SplashActivity.TARGET_PATH, ScanRecordUtils.SDCARD + path);
                                MainApplication.recordConfig = new RecordConfig(ScanRecordUtils.SDCARD + path, "", "");
                                goToPage();
                            }
                        } else {
                            value.showErrorMessage();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showDialog();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initDatas() {
        //拉去配置中心
        OkHttpUtils.getInstance().getApi().getRecordConfig(new HashMap<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<ArrayList<RecordConfig>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<ArrayList<RecordConfig>> value) {
                        if (value.isSuccess()) {
                            //解析映射配置系统
                            parseRecordConfigs(value);
                        } else {
                            value.showErrorMessage();
                            goToPage();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtils.show("出现错误,请重试~");
                        goToPage();
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 解析配置文件
     *
     * @param value
     */
    private void parseRecordConfigs(BaseResponse<ArrayList<RecordConfig>> value) {
        String brand = Build.BRAND;
        String model = Build.MODEL;
        if (value.data != null && value.data.size() > 0) {
            for (int i = 0; i < value.data.size(); i++) {
                RecordConfig recordConfig = value.data.get(i);
                //模糊查找 仅brand
                if (recordConfig.brand.equals(brand) && !TextUtils.isEmpty(recordConfig.brand)) {
                    MainApplication.recordConfig = recordConfig;
                }
                //精确查找 brand&model
                if (recordConfig.brand.equals(brand) && !TextUtils.isEmpty(recordConfig.model) && recordConfig.model.equals(model)) {
                    MainApplication.recordConfig = recordConfig;
                }
            }
            if (TextUtils.isEmpty(MainApplication.recordConfig.path)) {
                showNoSupportDialog();
            } else {
                goToPage();
            }
        } else {
            ToastUtils.show("配置系统出现错误~");
            goToPage();
        }
    }

    private void goToPage() {
        String token = SpUtils.getInstance(SplashActivity.this).getString("token");
        if (TextUtils.isEmpty(token)) {
            startActivity(new Intent(SplashActivity.this, LoginActivity.class));
            finish();
        } else {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }
    }

    private void showNoSupportDialog() {
        new AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("系统检测到您的手机未进行适配,请联系管理员")
                .setCancelable(false)
                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goToPage();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goToPage();
                    }
                })
                .create()
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
